package com.nanako.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanako.common.R;
import com.nanako.dao.DishMapper;
import com.nanako.dto.DishDto;
import com.nanako.entity.Dish;
import com.nanako.entity.DishFlavor;
import com.nanako.exception.CascadingDeleteException;
import com.nanako.service.DishFlavorService;
import com.nanako.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    public boolean updateDishFlavor(DishDto dishDto) {
        if (this.updateById(dishDto)) {
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, dishDto.getId());
            dishFlavorService.remove(wrapper);
            List<DishFlavor> flavors = dishDto.getFlavors();
            flavors = flavors.stream().map(flavor -> {
                flavor.setDishId(dishDto.getId());
                return flavor;
            }).toList();
            return dishFlavorService.saveBatch(flavors);
        }
        return false;
    }

    @Override
    public void deleteDishByIds(List<Long> ids) {
        // 循环遍历拿到的ids
        ids.forEach(id -> {
            // 获取该id的菜品
            // 判断该菜品是否为起售状态，如果是起售状态则不能删除，抛出异常回滚事务
            if (this.getById(id).getStatus() == 1) {
                throw new CascadingDeleteException("有菜品为起售状态，不能直接删除！！");
            }
            this.removeById(id);
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(wrapper);
        });
    }
}
